// pages/drink/drink.js
const util = require('../../utils/util.js');
const app = getApp();
const key = app.globalData.key;
const resurl = app.globalData.resurl;
let interstitialAd = null;
Page({
  insertScreenAdTimer:'',
  data: {
    isDelay: '',
    adverShow: true,
    bannerShow: true,
    showFinish: false,
    showMiss: false,
    show:false,
    showMask: false,
    timeShow: false,
    showMaskNext: false,
    userMoney:'',
    money: app.globalData.money,
    isClock:false,
    txt:'',
    number:'1',
    count:'',
    flag: false,
    clockInList:[],
    missSrc:[   '/images/image_cup_3.png',
                '/images/image_cup_3.png',
                '/images/image_cup_3.png',
                '/images/image_cup_3.png',
                '/images/image_cup_3.png',
                '/images/image_cup_3.png',
                '/images/image_cup_3.png',
            ],
    lastestSrc:['/images/image_cup_1.png','/images/image_cup_2.png','/images/image_cup_3.png','/images/image_cup_4.png'],
    arrList: [
      {
       water:'第一杯水',
       time:'08:00-08:45',
       content:'清理肠胃。经过一晚的消耗，起床时身体 正处于缺水状态，这时也是肾脏解毒的时 间段，喝杯水又利于清理肠胃、排除身体 毒素，促进身恢复正常的新陈代谢',
    },
    ],
    eventList:[
      {
        water:'第一杯水',
        time:'08:00-08:45',
        content:'清理肠胃。经过一晚的消耗，起床时身体 正处于缺水状态，这时也是肾脏解毒的时 间段，喝杯水又利于清理肠胃、排除身体 毒素，促进身恢复正常的新陈代谢',
     },
      {
      water:'第二杯水',
      time:'09:00-11:15',
      content:'提高活力，刚开始一天的工作，喝一杯水有利于让人充满活力，提高工作效率。同事这是肠胃排毒的时间段，可以帮助排除体内毒素',
   },
      {
      water:'第三杯水',
      time:'11:30-13:15',
      content:'增加饱腹，经过一上午的工作，在午餐之前可以喝一杯水，增加饱腹感，避免吃中餐时进食太多，同时这时也是心脏排毒的时间段，也可以帮助排除体内毒素',
   },
      {
      water:'第四杯水',
      time:'13:30-14:45',
      content:'促进消化，午餐很重要，但是也要适量的迟到八分饱，如果吃的太多也会给肠胃造成负担，所以记得在饭后20分钟喝杯水，促进消化',
   },
      {
      water:'第五杯水',
      time:'15:00-17:15',
      content:'振奋精神，下午茶时间记得喝杯咖啡或者喝杯温水，这时候也是小肠排毒的时间段，刚好补充第五杯水，帮助你排除体内的毒素',
   },
      {
      water:'第六杯水',
      time:'17:30-18:45',
      content:'减轻疲劳集合。一天的工作结束了，身体比较疲惫劳累，下班之前记得喝杯温开水，缓解一下因为工作带来的疲劳',
   },
      {
      water:'第七杯水',
      time:'19:00-20:15',
      content:'调节血液浓度，睡前两个小时内喝杯水，可以调节血液浓度，防止血液粘稠，补充睡眠时因出汗而失去水分',
   },
  ],
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    
    var now = new Date();
    var hours = now.getHours();
    var minutes = now.getMinutes();
    var timestamp = now.getTime();
    let [...missSrc] = [...this.data.missSrc];
    let [...lastestSrc] = [...this.data.lastestSrc];
    let [...arrList] = [...this.data.arrList];
    let [...eventList] = [...this.data.eventList];
    let number = this.data.number;
    let txt = this.data.txt;
    console.log(number);

    var btimestamp = function(begintime) {
      var bArray = begintime.split(":");
      //console.log(bArray);
      if(bArray.length !== 2){
        return false;
      }
      var b = new Date();
      b.setHours(bArray[0]);
      b.setMinutes(bArray[1]);
      var beginTime = b.getTime();
      return beginTime;
    }
    //console.log(btimestamp('08:00'));
    var etimestamp = function(endtime) {
      var eArray = endtime.split(":");
      if(eArray.length !== 2){
        return false;
      } 
      var e = new Date();
      e.setHours(eArray[0]);
      e.setMinutes(eArray[1]);
      var endTime = e.getTime();
      return endTime;
    }
   

    //第一杯水
    if( timestamp < btimestamp("08:00")) {
      arrList.splice(0,1,eventList[0]);
      this.setData({
        // missSrc,
        arrList:arrList.splice(0,1,eventList[0]),
      })
    }
    else if( timestamp > btimestamp('08:45') && timestamp<etimestamp('09:00') ){
      arrList.splice(0,1,eventList[0]);
      this.setData({
        arrList:arrList.splice(0,1,eventList[0]),
        
      })
    }
    else if(timestamp > btimestamp('08:00') && timestamp<etimestamp('08:45')){
      arrList.splice(0,1,eventList[0]);
      this.setData({
        number:1,
        arrList:arrList.splice(0,1,eventList[0]),
        // missSrc,
        isClock:true,
      })
    }
    //第二杯水
    if(timestamp > btimestamp('11:15') && timestamp<etimestamp('11:30')) {
      arrList.splice(0,1,eventList[1]);
      this.setData({
       arrList:arrList.splice(0,1,eventList[1]),
      })
    }
    else if(timestamp > btimestamp('09:00') && timestamp<etimestamp('11:15')){
      arrList.splice(0,1,eventList[1]);
      this.setData({
        number:2,
        arrList:arrList.splice(0,1,eventList[1]),
        isClock:true,
      })
    }
    //第三杯水
    if(timestamp > btimestamp('13:15') && timestamp < etimestamp('13:30')){
      arrList.splice(0,1,eventList[2]);
      this.setData({
        arrList:arrList.splice(0,1,eventList[2]),
      })
    }
    else if(timestamp > btimestamp("11:30") && timestamp < etimestamp("13:15")){
      arrList.splice(0,1,eventList[2]);
      missSrc.splice(2,1,lastestSrc[0]);
      this.setData({
       
        number:3,
        arrList:arrList.splice(0,1,eventList[2]),
        // missSrc,
        isClock:true,
      })
    }
    //第四杯水
    if(timestamp > btimestamp("14:45") && timestamp < etimestamp("15:00")){
      arrList.splice(0,1,eventList[3]);
      this.setData({
        arrList:arrList.splice(0,1,eventList[3]),
      })
    }
    else if(timestamp > btimestamp("13:30") && timestamp < etimestamp("14:45")){
      arrList.splice(0,1,eventList[3]);
      missSrc.splice(3,1,lastestSrc[0]);
      this.setData({
       
        number:4,
        arrList:arrList.splice(0,1,eventList[3]),
        // missSrc,
        isClock:true,
      })
    }
    //第五杯水
    if(timestamp > btimestamp("17:15") && timestamp < etimestamp("17:30")){
      arrList.splice(0,1,eventList[4]);
      this.setData({
        arrList:arrList.splice(0,1,eventList[5]),
      
      })
    }
    else if(timestamp > btimestamp("15:00") && timestamp <etimestamp("17:15")){
      missSrc.splice(4,1,lastestSrc[0]);
      arrList.splice(0,1,eventList[4]);
      this.setData({
        number:5,
        arrList:arrList.splice(0,1,eventList[4]),
        isClock:true,
      })
    }
    //第六杯水
    if(timestamp > btimestamp("18:45") && timestamp < etimestamp("19:00")){
      arrList.splice(0,1,eventList[5]);
      this.setData({
        arrList:arrList.splice(0,1,eventList[5]),
      })
    }
    else if(timestamp > btimestamp("17:30") && timestamp <etimestamp("18:45")){
      arrList.splice(0,1,eventList[5]);
      console.log(btimestamp("08:00"));
      this.setData({
        number:6,
        arrList:arrList.splice(0,1,eventList[5]),
        isClock:true,
      })
    }
    //第七杯水
    if(timestamp > btimestamp("20:15")){
      arrList.splice(0,1,eventList[6]);
      this.setData({
        arrList:arrList.splice(0,1,eventList[6]),
      })
    }
    else if(timestamp > btimestamp("19:00") && timestamp <etimestamp("20:15")){
      missSrc.splice(6,1,lastestSrc[0]);
      arrList.splice(0,1,eventList[6]);
      this.setData({
        number:7,
        arrList:arrList.splice(0,1,eventList[6]),
        isClock:true,
      })
    }
    this.setData({
      flag: true,
    })
  },
    // 关闭banner广告
    adClose: function () {
      this.setData({
        adverShow: false,
        // videoShow: true,
      })
    },
  //打卡点击事件
  todo:function (e) {
    var that = this;
    var number= e.currentTarget.dataset.number;
    var txt = e.currentTarget.dataset.txt;
    var clockInList = e.currentTarget.dataset.clockinlist;
    var [...missSrc] = [...e.currentTarget.dataset.misssrc];
    var [...lastestSrc] = [...e.currentTarget.dataset.lastestsrc];
    var count=number-1;
    missSrc.splice(count,1,lastestSrc[1]);
    that.setData({
      txt:'已打卡',
      missSrc,
      isClock:false,
    })
    console.log(txt);
    // console.log(clockInList[count].id)
    that.clockDrink(clockInList[count].id,count)

  },
  //喝水打卡 接口15
  clockDrink: function (jobId,count) {
    var that = this;
    var money = that.data.money;
    var userId = wx.getStorageSync("userId");
    var data15 = {
      deviceProperties: app.globalData.deviceProperties,
      user: {
        userId:userId,
        jobId: jobId,
      }
    }
    data15 = JSON.stringify(data15);
    data15 = util.base64_encode(data15);
    data15 = util.xxtea_encrypt(data15, key);
    wx.request({
      url: resurl + '/interface/sdkData?requestId=15&a=1&b=2',
      data:data15,
      header:{
        "content-type":"application/json",
        "dataType":"json",
      },
      method:"post",
      success: function(res) {
        res = util.xxtea_decrypt(res.data, key);
        res = util.base64_decode(res);
        res = JSON.parse(res);
        console.log(res);
        if(res.resultCode === 0) {
          res = JSON.parse(res.data);
          console.log(res);
          that.timeToast(res.reward);
          app.globalData.money = money + res.reward;
          that.setData({
            isClock:false,
            money: app.globalData.money,
          })
        }
        
      }
      })
  },
  back:function (){
    wx.navigateBack({
      delta: 1
    })
  },
  // 关闭时间未到和时间已经的弹窗
  close:function() {
    var that = this;
    var isDelay = that.data.isDelay;
    if(isDelay == 1) {
      var delayTimer = setInterval(function () {
        that.setData({
          show:false,
          showMiss: false,
          showMask: false,
          showFinish: false,
          bannerShow: true,
        })
        clearInterval(delayTimer);
      },2000)
    } else {
      that.setData({
        show:false,
        showMiss: false,
        showMask: false,
        showFinish: false,
        bannerShow: true,
      })
    }
  },
  choose:function(e) {
    var that = this;
    let arrList = e.currentTarget.dataset.arrlist;
    let eventList = e.currentTarget.dataset.eventlist;
    let missSrc = e.currentTarget.dataset.misssrc;
    let lastestSrc = e.currentTarget.dataset.lastestsrc;
    let txt = e.currentTarget.dataset.txt;
    let isClock = e.currentTarget.dataset.isclock;
    let now = new Date();
    let timeStamp = now.getTime();
    let index = e.currentTarget.dataset.index;
    that.getDrinkInfo(index);

    
    var beginTime = function(begintime) {
      var bArray = begintime.split(":");
      //console.log(bArray);
      if(bArray.length !== 2){
        return false;
      }
      var b = new Date();
      b.setHours(bArray[0]);
      b.setMinutes(bArray[1]);
      var btimeStamp = b.getTime();
      return btimeStamp;
    }
    var endTime = function(endtime) {
      var eArray = endtime.split(":");
      if(eArray.length !== 2){
        return false;
      } 
      var e = new Date();
      e.setHours(eArray[0]);
      e.setMinutes(eArray[1]);
      var etimesTamp = e.getTime();
      return etimesTamp;
    }
    //1
    if(index === 0){
      if(timeStamp < beginTime("08:00")) {
        that.setData ({
        })
      }
      else if(timeStamp > beginTime("08:00") && timeStamp < endTime("08:45")){
        arrList.splice(0,1,eventList[index]);
        that.setData ({
          arrList:arrList.splice(0,1,eventList[index]),
        })
      }
      else if (timeStamp > endTime("08:45")){
        arrList.splice(0,1,eventList[index]);
        that.setData({
          arrList:arrList.splice(0,1,eventList[index]),
        })
      }
    }
    //2
    if(index === 1){
      if(timeStamp < beginTime("09:00") ){
        arrList.splice(0,1,eventList[index]);
        that.setData({
          arrList:arrList.splice(0,1,eventList[index]),
        })
      }
      else if(timeStamp > beginTime("09:00") && timeStamp < endTime("11:15")){
        arrList.splice(0,1,eventList[index]);
        that.setData ({
          arrList:arrList.splice(0,1,eventList[index]),
        })
      }
    else if(timeStamp > endTime("11:15")) {
      arrList.splice(0,1,eventList[index]);
      that.setData({
          arrList:arrList.splice(0,1,eventList[index]),
        })
    }
  }
    //3
    if(index === 2){
      if (timeStamp < beginTime("11:30")){
        arrList.splice(0,1,eventList[index]);
        that.setData ({
          arrList:arrList.splice(0,1,eventList[2]),
        })
      }
      else if(timeStamp > beginTime("11:30") && timeStamp < endTime("13:15")){
        arrList.splice(0,1,eventList[index]);
        that.setData ({
          arrList:arrList.splice(0,1,eventList[index]),
        })
      }
      else if (timeStamp > endTime("13:15")){
        arrList.splice(0,1,eventList[index]);
        that.setData({
          arrList:arrList.splice(0,1,eventList[index]),
        })
      }
    }
    //4
    if(index === 3){
      if (timeStamp < beginTime("13:30")){
        arrList.splice(0,1,eventList[index]);
        that.setData ({
          arrList:arrList.splice(0,1,eventList[index]),
        })
      }
      else if(timeStamp > beginTime("13:30") && timeStamp < endTime("14:45") ){
        arrList.splice(0,1,eventList[index]);
        that.setData ({
          arrList:arrList.splice(0,1,eventList[index]),
        })
      }
      else if (timeStamp > endTime("14:45")){
        arrList.splice(0,1,eventList[index]);
        that.setData({
          arrList:arrList.splice(0,1,eventList[index]),
        })
      }
    }
    //5
    if(index === 4){
      if (timeStamp < beginTime("15:00")){
        arrList.splice(0,1,eventList[index]);
        that.setData ({
          arrList:arrList.splice(0,1,eventList[index]),
        })
      }
      else if(timeStamp > beginTime("15:00") && timeStamp < endTime("17:15")){
        arrList.splice(0,1,eventList[index]);
        that.setData ({
          arrList:arrList.splice(0,1,eventList[index]),
        })
      }
      else if (timeStamp > endTime("17:15")){
        arrList.splice(0,1,eventList[index]);
        that.setData({
          arrList:arrList.splice(0,1,eventList[index]),
        })
      }
    }
    //6
    if(index === 5){
      if (timeStamp < beginTime("17:30")){
        arrList.splice(0,1,eventList[index]);
        that.setData ({
          arrList:arrList.splice(0,1,eventList[index]),
        })
      }
      else if(timeStamp > beginTime("17:30") && timeStamp < endTime("18:45")){
        arrList.splice(0,1,eventList[index]);
        that.setData ({
          arrList:arrList.splice(0,1,eventList[index]),
        })
      }
      else if (timeStamp > endTime("18:45")){
        arrList.splice(0,1,eventList[index]);
        that.setData({
          arrList:arrList.splice(0,1,eventList[index]),
        })
      }
    }
    //7
    if(index === 6){
      if (timeStamp < beginTime("19:00")){
        arrList.splice(0,1,eventList[index]);
        that.setData ({
          arrList:arrList.splice(0,1,eventList[index]),
        })
      }
      else if(timeStamp > beginTime("19:00") && timeStamp < endTime("20:15")){
        arrList.splice(0,1,eventList[index]);
        that.setData ({
          arrList:arrList.splice(0,1,eventList[index]),
        })
      }
      else if (timeStamp > endTime("20:15")){
        arrList.splice(0,1,eventList[index]);
        that.setData({
          arrList:arrList.splice(0,1,eventList[index]),
        })
      }
    }
  },
  //显示打卡时间已经错过
  missToast: function () {
    var that = this;
    that.setData({
      showMask: true,
      showMiss: true,
    })
  },
  //显示打卡时间未到
  futureToast: function () {
    var that = this;
    that.setData({
      showMask: true,
      show: true,
    })
  },
  finishToast: function () {
    var that = this;
    that.setData({
      showMask: true,
      showFinish: true,
    })
  },
  
  // 获取喝水打卡显示页面，用于底部点击的显示状态
  getDrinkInfo: function (index) {
    //获取喝水打卡页面 接口14
    var that = this;
    var missSrc = that.data.missSrc;
    var lastestSrc = that.data.lastestSrc;
    var userId = wx.getStorageSync("userId");
    var data14 = {
      deviceProperties: app.globalData.deviceProperties,
      user: {
        userId:userId,
        clockType: 11,
      }
    }
    data14 = JSON.stringify(data14);
    data14 = util.base64_encode(data14);
    data14 = util.xxtea_encrypt(data14, key);
    wx.request({
      url: resurl + '/interface/sdkData?requestId=14&a=1&b=2',
      data:data14,
      header:{
        "content-type":"application/json",
        "dataType":"json",
      },
      method:"post",
      success: function(res) {
        res = util.xxtea_decrypt(res.data, key);
        res = util.base64_decode(res);
        res = JSON.parse(res);
        console.log(res);
        if(res.resultCode === 0) {
          res = JSON.parse(res.data);
          console.log(res);
          // console.log(res.clockInList[index].clockType+10000);
          if ( res.clockInList[index].clockType === 0) {
            that.missToast();
            that.setData({
              txt:'已错过',
              isClock:false,
            })
          } else if (res.clockInList[index].clockType === 1) {
            missSrc.splice(index,1,lastestSrc[1]);
            that.finishToast();
            that.setData ({
              txt:'已打卡',
              isClock:false,
              missSrc,
            })
          } else if (res.clockInList[index].clockType === 2) {
            that.futureToast();
            that.setData ({
              txt:'未到时间',
              isClock:false,
            })
          } else if (res.clockInList[index].clockType === 3) {
            that.setData ({
              txt:'第'+(index+1)+'杯水打卡',
              isClock:true,
            })
          }
          that.setData({
            clockInList: res.clockInList,
          })
        }
      }
      })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    var that = this;
    var isDelay = wx.getStorageSync("isDelay");
      //获取喝水打卡页面 接口14
    that.setData({
      money: app.globalData.money,
      isDelay,
    })
    var beginTime = function(begintime) {
      var bArray = begintime.split(":");
      //console.log(bArray);
      if(bArray.length !== 2){
        return false;
      }
      var b = new Date();
      b.setHours(bArray[0]);
      b.setMinutes(bArray[1]);
      var btimeStamp = b.getTime();
      return btimeStamp;
    }
    var now = new Date();
    var timeStamp = now.getTime();
    var nowNum;
    if( timeStamp < beginTime("08:00")) {
      nowNum = 1;
    }
    if( timeStamp > beginTime("08:00")) {
      nowNum = 1;
    }
    if( timeStamp > beginTime("09:00")) {
      nowNum = 2;
    }
    if( timeStamp > beginTime("11:30")) {
      nowNum = 3;
    }
    if( timeStamp > beginTime("13:30")) {
      nowNum = 4;
    }
    if( timeStamp > beginTime("15:00")) {
      nowNum = 5;
    }
    if( timeStamp > beginTime("17:30")) {
      nowNum = 6;
    }
    if( timeStamp > beginTime("19:00")) {
      nowNum = 7;
    }
    var userId = wx.getStorageSync("userId");
    var data14 = {
      deviceProperties: app.globalData.deviceProperties,
      user: {
        userId:userId,
        clockType: 11,
      }
    }
    data14 = JSON.stringify(data14);
    data14 = util.base64_encode(data14);
    data14 = util.xxtea_encrypt(data14, key);
    wx.request({
      url: resurl + '/interface/sdkData?requestId=14&a=1&b=2',
      data:data14,
      header:{
        "content-type":"application/json",
        "dataType":"json",
      },
      method:"post",
      success: function(res) {
        res = util.xxtea_decrypt(res.data, key);
        res = util.base64_decode(res);
        res = JSON.parse(res);
        console.log(res);
        if(res.resultCode === 0) {
          res = JSON.parse(res.data);
          console.log(res);
          var lastestSrc = that.data.lastestSrc;
          var missSrc = that.data.missSrc;
         
          for(var index = 0; index < nowNum; index ++ ) {
            if ( res.clockInList[index].clockType === 0) {
              missSrc.splice(index,1,lastestSrc[3]);
              that.setData({
                txt:'已错过',
                missSrc,
                
              })
            } else if (res.clockInList[index].clockType === 1) {
              missSrc.splice(index,1,lastestSrc[1]);
              that.setData ({
                txt:'已打卡',
                missSrc,
                isClock: false,
              })
            } else if (res.clockInList[index].clockType === 2) {
              missSrc.splice(index,1,lastestSrc[2]);
              that.setData ({
                txt:'未到时间',
                missSrc,
              })
            } else if (res.clockInList[index].clockType === 3) {
              missSrc.splice(index,1,lastestSrc[0]);
              that.setData ({
                txt:'第'+(index+1)+'杯水打卡',
                // txt:'我的错？',
                missSrc,
                isClock: true,
              })
            }
          }
          that.setData({
            clockInList: res.clockInList,
          })
        }
      }
      })
      var count = 0;
    var insertScreenAdTimer = setInterval(function () {
      count ++;
      console.log(count);
      if(count > 3) {
        that.insertScreenAD();
        clearInterval(insertScreenAdTimer);
      }
    },1000)
    that.insertScreenAdTimer = insertScreenAdTimer;
  },
  insertScreenAD: function () {
    // 在页面onLoad回调事件中创建插屏广告实例
    if (wx.createInterstitialAd) {
      interstitialAd = wx.createInterstitialAd({
        adUnitId: 'adunit-1cc4cb154d00aa08'
      })
      interstitialAd.onLoad(() => { })
      interstitialAd.onError((err) => { })
      interstitialAd.onClose(() => { })
    }

    // 在适合的场景显示插屏广告
    if (interstitialAd) {
      interstitialAd.show().catch((err) => {
        console.error(err)
      })
    }
  },
   // 显示领取元宝奖励的弹窗
   timeToast: function (a) {
    var that = this;
    var money = that.data.money;
     that.setData({  
         timeShow: true,
         showMaskNext: true,
         money:money + a,
         timeyuanbao: a,
         })
     var userMoney = Math.floor((money+a)/10000*100)/100;
     that.setData({
       userMoney: userMoney,
     })
  },
   // 关闭领取奖励的弹窗
   clickcloseReward:function() {
     var that = this;
     var isDelay = that.data.isDelay;
     console.log(isDelay);
    if(isDelay == 1) {
      var delayTimer = setInterval(function () {
        that.setData({
          timeShow:false,
          showMaskNext:false,
        })
        clearInterval(delayTimer);
      },2000)
    } else {
      that.setData({
        timeShow:false,
        showMaskNext:false,
      })
    }
  },
  closeBanner: function () {
    this.setData({
      bannerShow: false,
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    var that = this;
    clearInterval(that.insertScreenAdTimer);
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    var that = this;
    clearInterval(that.insertScreenAdTimer);
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})